import cheerio from 'cheerio'
import config  from 'config'
import {parseFilesFromMetaXml} from './file'
const nextcloud = config.get('nextcloud')

export const getTrashes = async (client,user,path,pattern)=>{
    let baseUrl = `/trashbin/${user.id}/trash`
    let files = await client.customRequest(baseUrl + path, {
        method: "PROPFIND",
        headers: {
            Accept: "text/xml",
            Depth: "infinity",
            "Content-Type": "application/xml; charset=utf-8"
        },
        data: `<?xml version="1.0"?>
                    <d:propfind  xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
                      <d:prop>
                        <oc:fileid />
                        <nc:trashbin-filename />
                        <nc:trashbin-original-location />
                        <d:getlastmodified />
                        <d:getcontenttype />
                        <oc:size />
                      </d:prop>
                    </d:propfind>`,
        responseType: "text"
    });
    files = parseFilesFromMetaXml(files,`/remote.php/dav${baseUrl}`)
    return files;
}


export const restoreTrash = async (client,user,filename)=>{
    let destination = nextcloud.host + `/remote.php/dav/trashbin/${user.id}/restore/${encodeURIComponent(filename)}`
    await client.customRequest(`/trashbin/${user.id}/trash/${(filename)}`, {
        method: "MOVE",
        headers: {
            "Accept": "text/xml",
            "Content-Type": "application/xml; charset=utf-8",
            "Destination":destination
        },
        responseType: "text"
    })
}


export const delTrash = async (client,user,filename)=>{
    await client.customRequest(`/trashbin/${user.id}/trash/${filename}`, {
        method: "DELETE",
        headers: {
            "Accept": "text/xml",
            "Content-Type": "application/xml; charset=utf-8"
        },
        responseType: "text"
    })
}

export const emptyTrash = async (client,user)=>{
    await client.customRequest(`/trashbin/${user.id}/trash`, {
        method: "DELETE",
        headers: {
            "Accept": "text/xml",
            "Content-Type": "application/xml; charset=utf-8"
        },
        responseType: "text"
    })
}
